﻿/*
' Copyright (c) 2011  DotNetNuke Corporation
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using DotNetNuke.Security.Roles;

using System.Web.UI.WebControls;
using System.Data.SqlClient;
using DotNetNuke.Framework.Providers;
using DotNetNuke.Modules.PersonalAssistants.Components;

using System.Net.Mail;

namespace DotNetNuke.Modules.PersonalAssistants
{
    public partial class EditPAProfile : PersonalAssistantsModuleBase//, IActionable
    {
        private const string providerType = "data";
        private ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(providerType);
        private string connectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                { 
                    //View0 - Intro for PersonalAssistants (Admin drop through to View1)
                    //View1 - Admin, select User or EntryId to Edit or create Profile
                    //View2 - PersonalAssistant profile form (Admin and PA)
                    //View3 - Update completed, continue to main page
                    //View4 - 
                    //EditPersonalAssistantsMultiView.SetActiveView(View1);

                    Trace.Warn("Page_Load");
                    lblUsername.Text = UserInfo.Username.ToString();
                    lblEmail.Text = UserInfo.Email.ToString();

                    Provider provider = (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider];
                    connectionString = DotNetNuke.Common.Utilities.Config.GetConnectionString();

                    SqlConnection commonConnection = new SqlConnection();
                    commonConnection.ConnectionString = connectionString;
                    SqlCommand sharedSqlCommand;
                    SqlDataReader sharedSqlDataReader;

                    int paModuleId = this.ModuleId;
                    if (paModuleId != null)
                    {
                        //set up the User's Profile selection
                        sharedSqlCommand = new SqlCommand("SELECT Username, EntryId FROM PersonalAssistants where ModuleId = " + paModuleId.ToString() + " AND deleted != 'Yes' ORDER BY Username", commonConnection);
                        commonConnection.Open();
                        sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                        ipUsernameForProfile.DataSource = sharedSqlDataReader;
                        ipUsernameForProfile.DataBind();
                        // add an empty item to aid selection
                        ipUsernameForProfile.Items.Insert(0, "");
                        commonConnection.Close();
                        sharedSqlDataReader.Close();
                        lblConfigMissing1.Visible = false;
                        if (ipUsernameForProfile.Items.Count == 0)
                        {
                            lblConfigMissing1.Visible = true;
                            ipUsernameForProfile.Visible = false;
                        }
                        // Entry number for PA Profile to edit
                        commonConnection.Open(); 
                        sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                        ipEntryNumberForProfile.DataSource = sharedSqlDataReader;
                        ipEntryNumberForProfile.DataBind();
                        ipEntryNumberForProfile.Items.Insert(0, "");
                        commonConnection.Close();
                        sharedSqlDataReader.Close();
                        lblConfigMissing2.Visible = false;
                        if (ipEntryNumberForProfile.Items.Count == 0) {
                            lblConfigMissing2.Visible = true;
                            ipEntryNumberForProfile.Visible = false;
                        }
                        //upapproved Profiles
                        sharedSqlCommand = new SqlCommand("SELECT Username, EntryId FROM PersonalAssistants where ModuleId = " + paModuleId.ToString() + "AND ProfileApproved != 'Yes' AND deleted != 'Yes' ORDER BY Username", commonConnection);
                        commonConnection.Open();
                        sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                        ipUsernameForUnapprovedProfile.DataSource = sharedSqlDataReader;
                        ipUsernameForUnapprovedProfile.DataBind();
                        ipUsernameForUnapprovedProfile.Items.Insert(0,"");
                        commonConnection.Close();
                        sharedSqlDataReader.Close();
                        lblConfigMissing3.Visible = false;
                        if (ipEntryNumberForProfile.Items.Count == 0)
                        {
                            lblConfigMissing3.Visible = true;
                            ipUsernameForUnapprovedProfile.Visible = false;
                            
                        }

                    }

                    
                    // Set up inputs
                    if (!UserId.Equals(-1))
                    {
                        //(1)
                        ipUsername.Text = UserInfo.Username.ToString();
                        //(2)
                        ipEmail.Text = UserInfo.Email.ToString();
                    }

                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'LOCATIONS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    //(3)
                    ipPALocation.DataSource = sharedSqlDataReader;
                    ipPALocation.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //(4)
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'LOCATIONS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    ipPALocations.DataSource = sharedSqlDataReader;
                    ipPALocations.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //(5)
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'TASKS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    ipTaskList.DataSource = sharedSqlDataReader;
                    ipTaskList.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //(7)
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'AVAILABLE' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    ipHoursAvailable.DataSource = sharedSqlDataReader;
                    ipHoursAvailable.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //(8)
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'DAYS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    ipDaysAvailable.DataSource = sharedSqlDataReader;
                    ipDaysAvailable.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();
                    // Admin should drop straight through to select a Profile to Edit
                    if(userIsAdministrator())
                    {
                        EditPersonalAssistantsMultiView.SetActiveView(View1);
                    }


                }
                catch (Exception exc) //Module failed to load
                {
                    Exceptions.ProcessModuleLoadException(this, exc);
                }//end try catch

            }
        }
        protected void btnReturnPressed(object sender, EventArgs e)
        {
            if(userIsAdministrator())
                EditPersonalAssistantsMultiView.SetActiveView(View1);
            else
                EditPersonalAssistantsMultiView.SetActiveView(View0);
        }
        protected void btnAdminCreatePAProfile(object sender, EventArgs e)
        {
            if (userIsAdministrator())
            {
                lblErrorMessage.Visible = false;
                PersonalAssistantProfile oProfile = new PersonalAssistantProfile();
                fillEditForm(oProfile);
                EditPersonalAssistantsMultiView.SetActiveView(View2);
            }

        }
        
        protected void btnPAContinuePressed(object sender, EventArgs e) {
            // Personal Asistants are not allowed to modify their Username and Email address
            // Personal Assistants are not allowed to approve their profile
            ipUsername.Enabled = false;
            ipEmail.Enabled = false;
            ipProfileApproved.Visible = false;
            lblApproveProfile.Visible = false;
            int paModuleId = this.ModuleId;                
            if (paModuleId != null)
            {
                FeatureController oController = new FeatureController();
                PersonalAssistantProfile oProfile =
                    oController.GetPAProfileByUsername(paModuleId, UserInfo.Username.ToString());
                if(oProfile != null)
                    fillEditForm(oProfile);
            }
            //give some confirmation and then on to the Home screen
            lblErrorMessage.Visible = false;
            EditPersonalAssistantsMultiView.SetActiveView(View2);
        }
        protected void selectedUsername(object sender, EventArgs e)
        {

            FeatureController oController = new FeatureController();
            //Detect the ModuleId for DB, and setup the User's that have Profiles for Editing
            int paModuleId = this.ModuleId;
            if (paModuleId != null)
            {
                if(ipUsernameForProfile.SelectedValue.ToString().Length > 0){
                    PersonalAssistantProfile oProfile =
                        oController.GetPAProfile(paModuleId, int.Parse(ipUsernameForProfile.SelectedValue.ToString()));
                    fillEditForm(oProfile);                
                }

            }
            lblErrorMessage.Visible = false;
            EditPersonalAssistantsMultiView.SetActiveView(View2);


        }
        protected void selectedUnapprovedUsername(object sender, EventArgs e)
        {

            FeatureController oController = new FeatureController();
            //Detect the ModuleId for DB, and setup the User's that have Profiles for Editing
            int paModuleId = this.ModuleId;
            if (paModuleId != null)
            {
                if(ipUsernameForUnapprovedProfile.SelectedValue.ToString().Length > 0){
                    PersonalAssistantProfile oProfile =
                        oController.GetPAProfile(paModuleId, int.Parse(ipUsernameForUnapprovedProfile.SelectedValue.ToString()));
                    fillEditForm(oProfile);
                }
            }
            lblErrorMessage.Visible = false;
            EditPersonalAssistantsMultiView.SetActiveView(View2);


        }
        protected void selectedEntryId(object sender, EventArgs e)
        {
            //for Admin only, allowing them to edit a Profile by EntryId
            FeatureController oController = new FeatureController();
            //Detect the ModuleId for DB, and setup the User's that have Profiles for Editing
            int paModuleId = this.ModuleId;
            if (paModuleId != null)
            {
                if (ipEntryNumberForProfile.SelectedValue.ToString().Length > 0) 
                {
                    PersonalAssistantProfile oProfile =
                        oController.GetPAProfile(paModuleId, int.Parse(ipEntryNumberForProfile.SelectedValue.ToString()));
                    fillEditForm(oProfile);
                }
                
            }
            lblErrorMessage.Visible = false;
            EditPersonalAssistantsMultiView.SetActiveView(View2);

        }
        protected void fillEditForm(PersonalAssistantProfile oProfile)
        {

                //hidden Entry number
                ipEntryId.Text = oProfile.EntryId.ToString();
                //now set up the inputs
                ipALittleBitAboutPANotes.Text = oProfile.ALittleBitAboutMyself.ToString();
                ipBarredByISA.SelectedValue = oProfile.BarredByISA.ToString();
                ipCarOwner.SelectedValue = oProfile.CarOwner.ToString();
                oProfile.DateOfPAUpdate = DateTime.Now;
                oProfile.DateTime = DateTime.Now;
                //// Days available

                foreach (ListItem lstItm in ipDaysAvailable.Items)
                {
                    if (oProfile.DaysAvailable.Contains(lstItm.ToString()) && !lstItm.ToString().Equals(" "))
                        lstItm.Selected = true;
                    else
                        lstItm.Selected = false;
                }

                ipDaysRequired.Text = oProfile.DaysPerWeek.ToString();
                ipDrivingLicence.SelectedValue = oProfile.DrivingLicenceHeld.ToString();
                ipECRcheck.SelectedValue = oProfile.ECRWilling.ToString();
                ipEmail.Text = oProfile.Email.ToString();
                ipEmergencyCallout.SelectedValue = oProfile.EmergencyCallout.ToString();
                ipHoursRequired.Text = oProfile.HoursPerDay.ToString();
                ipOtherLanguages.SelectedValue = oProfile.Languages.ToString();
                ipLateNights.SelectedValue = oProfile.LateNights.ToString();
                //// Locations
                foreach (ListItem lstItm in ipPALocations.Items)
                {
                    if (oProfile.Locations.ToString().Contains(lstItm.Text.ToString()) && !lstItm.ToString().Equals(" "))
                        lstItm.Selected = true;
                    else
                        lstItm.Selected = false;
                }
                ipMaleOrFemale.SelectedValue = oProfile.MaleOrFemale.ToString();
                ipMeatProducts.SelectedValue = oProfile.MeatProducts.ToString();
                ipOvernightWakingNights.SelectedValue = oProfile.OvernightWakingNights.ToString();
                ipPALocation.SelectedValue = oProfile.PALocation.ToString();
                ipPermissionForUK.SelectedValue = oProfile.PermissionForUK.ToString();
                ipProfileApproved.SelectedValue = oProfile.ProfileApproved.ToString();
                ipReferencesAvailable.SelectedValue = oProfile.Provide2References.ToString();
                ipPublishProfile.SelectedValue = oProfile.PublishThisProfile.ToString();
                ipReferenceNotes.Text = oProfile.ReferenceNotes.ToString();
                ipSchoolHolidays.SelectedValue = oProfile.SchoolHolidays.ToString();
                ipQualificationsAndTrainingNotes.Text = oProfile.SkillNotes.ToString();
                ipSmoker.SelectedValue = oProfile.Smoker.ToString();
                ipTaskNotes.Text = oProfile.TaskNotes.ToString();
                //// Tasks
                foreach (ListItem lstItm in ipTaskList.Items)
                {
                    if (oProfile.Tasks.ToString().Contains(lstItm.Text.ToString()) && !lstItm.ToString().Equals(" "))
                        lstItm.Selected = true;
                    else
                        lstItm.Selected = false;
                }
                ipTermTime.SelectedValue = oProfile.TermTime.ToString();
                ////Hours available
                foreach (ListItem lstItm in ipHoursAvailable.Items)
                {
                    if (oProfile.TimesAvailable.ToString().Contains(lstItm.Text.ToString()) && !lstItm.ToString().Equals(" "))
                        lstItm.Selected = true;
                    else
                        lstItm.Selected = false;
                }

                ipUsername.Text = oProfile.Username.ToString();
                ipWorkPatternNotes.Text = oProfile.WorkpatternNotes.ToString();
                ipAddressYears.Text = oProfile.YearsResident.ToString();
            
        }

        protected void submittedProfile(object sender, EventArgs e)
        {
            Trace.Warn("submittedProfile");

            PersonalAssistantProfile oProfile = new PersonalAssistantProfile();
            oProfile.ALittleBitAboutMyself = ipALittleBitAboutPANotes.Text.ToString();
            oProfile.BarredByISA = ipBarredByISA.SelectedValue.ToString();
            oProfile.CarOwner = ipCarOwner.SelectedValue.ToString();
            oProfile.DateOfPAUpdate = DateTime.Now;
            oProfile.DateTime = DateTime.Now;
            // Days available
            foreach (ListItem lstItm in ipDaysAvailable.Items)
            {
                if (lstItm.Selected)
                    oProfile.DaysAvailable += (lstItm.Text.ToString() + ",");
            }
            if (oProfile.DaysAvailable.EndsWith(","))
                oProfile.DaysAvailable = oProfile.DaysAvailable.TrimEnd(',');

            oProfile.DaysPerWeek = ipDaysRequired.Text.ToString();
            oProfile.DrivingLicenceHeld = ipDrivingLicence.SelectedValue.ToString();
            oProfile.ECRWilling = ipECRcheck.SelectedValue.ToString();
            oProfile.Email = ipEmail.Text.ToString();
            oProfile.EmergencyCallout = ipEmergencyCallout.SelectedValue.ToString();
            oProfile.HoursPerDay = ipHoursRequired.Text.ToString();
            oProfile.IsPersonalAssistant = "Yes";
            oProfile.Languages = ipOtherLanguages.SelectedValue.ToString();
            oProfile.LateNights = ipLateNights.SelectedValue.ToString();
            // Locations
            foreach (ListItem lstItm in ipPALocations.Items)
            {
                if (lstItm.Selected)
                    oProfile.Locations += (lstItm.Text.ToString() + ",");
            }
            if (oProfile.Locations.EndsWith(","))
                oProfile.Locations = oProfile.Locations.TrimEnd(',');
            oProfile.MaleOrFemale = ipMaleOrFemale.SelectedValue.ToString();
            oProfile.MeatProducts = ipMeatProducts.SelectedValue.ToString();
            oProfile.OvernightWakingNights = ipOvernightWakingNights.SelectedValue.ToString();
            oProfile.PALocation = ipPALocation.Text.ToString();
            oProfile.PermissionForUK = ipPermissionForUK.SelectedValue.ToString();
            // Updates by PA reset the Approved flag
            if (userIsPersonalAssistant())
                oProfile.ProfileApproved = "No";
            else
                oProfile.ProfileApproved = ipProfileApproved.SelectedValue.ToString();
            oProfile.Provide2References = ipReferencesAvailable.SelectedValue.ToString();
            oProfile.PublishThisProfile = ipPublishProfile.SelectedValue.ToString();
            oProfile.ReferenceNotes = ipReferenceNotes.Text.ToString();
            oProfile.SchoolHolidays = ipSchoolHolidays.SelectedValue.ToString();
            oProfile.ServiceRequired = "";
            oProfile.SkillNotes = ipQualificationsAndTrainingNotes.Text.ToString();
            oProfile.Smoker = ipSmoker.SelectedValue.ToString();
            oProfile.TaskNotes = ipTaskNotes.Text.ToString();
            // Tasks
            foreach (ListItem lstItm in ipTaskList.Items)
            {
                if (lstItm.Selected)
                    oProfile.Tasks += (lstItm.Text.ToString() + ",");
            }
            if (oProfile.Tasks.EndsWith(","))
                oProfile.Tasks = oProfile.Tasks.TrimEnd(',');
            oProfile.TermTime = ipTermTime.SelectedValue.ToString();
            //Hours available
            foreach (ListItem lstItm in ipHoursAvailable.Items)
                if (lstItm.Selected)
                    oProfile.TimesAvailable += lstItm.Text.ToString() + ",";
            if (oProfile.TimesAvailable.EndsWith(","))
                oProfile.TimesAvailable = oProfile.TimesAvailable.TrimEnd(',');
            oProfile.Username = ipUsername.Text.ToString();
            oProfile.WorkpatternNotes = ipWorkPatternNotes.Text.ToString();
            oProfile.YearsResident = ipAddressYears.Text.ToString();
            oProfile.Deleted = "No";
            //Detect the ModuleId for DB, and setup the User's that have Profiles for Editing
            int paModuleId = this.ModuleId;
            if(paModuleId != 0){
            // Updating the Profile
                oProfile.ModuleId = paModuleId;

                if (int.Parse(ipEntryId.Text.ToString()) != 0)
                {   
                // Updating module
                    oProfile.EntryId = int.Parse(ipEntryId.Text.ToString());
                    
                    FeatureController oController = new FeatureController();
                    Trace.Warn("UpdatingPAProfile");
                    Trace.Write("UpdatingPAProfile");

                    oController.UpdatePAProfile(oProfile);
                    if(oProfile.ProfileApproved.ToString().Contains("Yes"))
                        sendMailMessage(oProfile, "approve");
                    else
                        sendMailMessage(oProfile, "update");
                }
                else {
                // Creating new Profile 
                    FeatureController oController = new FeatureController();
                    PersonalAssistantProfile oExistingProfile =
                    oController.GetPAProfileByUsername(paModuleId, oProfile.Username.ToString());
                    if (oExistingProfile == null)
                    {
                        oController.InsertPAProfile(oProfile);
                        sendMailMessage(oProfile, "create");
                    }
                    else { 
                        // User already has a Profile
                        lblErrorMessage.Visible = true;
                        return;
                    }
                }
            }


            if (userIsAdministrator())
                EditPersonalAssistantsMultiView.SetActiveView(View1);
            else
                EditPersonalAssistantsMultiView.SetActiveView(View3);
        }

        private bool sendMailMessage(PersonalAssistantProfile oProfile, string messageType) {
            MailDetails mailDetails = new MailDetails();
            if (mailDetails.MailDetailsComplete && (mailDetails.SendEmailsOut == "Yes"))
            {
                MailMessage newMail = new MailMessage();

                newMail.To.Add(oProfile.Email.ToString());
                newMail.CC.Add(mailDetails.AdminEmail);
                String mailText1;
                String mailText2;

                switch (messageType)
                {
                    case "create":
                        mailText1 = mailDetails.CreatedSubject;
                        mailText2 = mailDetails.CreatedBody;
                        break;
                    case "update":
                        mailText1 = mailDetails.UpdatedSubject;
                        mailText2 = mailDetails.UpdatedBody;
                        break;
                    case "approve":
                        mailText1 = mailDetails.ApprovedSubject;
                        mailText2 = mailDetails.ApprovedBody;
                        break;
                    default:
                        mailText1 = "";
                        mailText2 = "";
                        break;
                }
                mailText1.Replace("[USERNAME]", oProfile.Username.ToString());
                mailText2.Replace("[USERNAME]", oProfile.Username.ToString());
                newMail.Subject = mailText1.ToString();
                newMail.Body = mailText2.ToString();
                newMail.From = new MailAddress(mailDetails.AdminEmail.ToString(), "SYCIL Lifestyle Choices");
                newMail.IsBodyHtml = true;
                SmtpClient SmtpSender = new SmtpClient();
                SmtpSender.Send(newMail);
            }
            return mailDetails.MailDetailsComplete;

        }
        protected void returnToTheHomePage(object sender, EventArgs e){
            object paHomePageUrl = Settings["PersonalAssistantsHomePageUrl"];
            if (paHomePageUrl != null)
            {
                Response.Redirect(paHomePageUrl.ToString(), true);
            }          
        }
        private bool userIsPersonalAssistant() {
            if (UserInfo.IsInRole("Administrators") || UserInfo.IsInRole("PA Register Administration")) 
                return false;
            else
                return true;
        }

        private bool userIsAdministrator() {
            if (UserInfo.IsInRole("Administrators") || UserInfo.IsInRole("PA Register Administration"))
                return true;
            else
                return false;
        }



        #region Optional Interfaces

        //public ModuleActionCollection ModuleActions
        //{
        //    get
        //    {
        //        ModuleActionCollection Actions = new ModuleActionCollection();
        //        Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
        //        return Actions;
        //    }
        //}

        #endregion

    }
}